package com.atguigu.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.cart.feign.ProductFeignService;
import com.atguigu.gulimall.cart.interceptor.CartInterceptor;
import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.to.UserInfoTo;
import com.atguigu.gulimall.cart.vo.CartItemVo;
import com.atguigu.gulimall.cart.vo.CartVo;
import com.atguigu.gulimall.cart.vo.SkuInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author phil
 * @create 2022-01-15 14:16
 */
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    ThreadPoolExecutor executor;

    private final String CART_PREFIX = "gulimall:cart:";

    @Override
    public CartItemVo addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String res = (String)cartOps.get(skuId.toString());
        //购物车新增新商品
        if(res == null){
            CartItemVo cartItemVo = new CartItemVo();

            //异步编排，同时调用远程服务
            CompletableFuture<Void> getSkuInfo = CompletableFuture.runAsync(() -> {
                //1.远程调用，查询商品信息
                R r = productFeignService.getSkuInfo(skuId);
                if (r.getCode() == 0) {
                    SkuInfoVo skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                    });
                    cartItemVo.setSkuId(skuId);
                    cartItemVo.setTitle(skuInfo.getSkuTitle());
                    cartItemVo.setImage(skuInfo.getSkuDefaultImg());
                    cartItemVo.setPrice(skuInfo.getPrice());
                    cartItemVo.setCount(num);
                }
            }, executor);

            CompletableFuture<Void> getSkuAttrs = CompletableFuture.runAsync(() -> {
                //2.远程调用，查sku属性
                List<String> skuSaleAttrValue = productFeignService.getSkuSaleAttrValue(skuId);
                cartItemVo.setSkuAttrValues(skuSaleAttrValue);
            }, executor);
            CompletableFuture.allOf(getSkuAttrs,getSkuInfo).get();

            //3.将购物车信息存到redis中
            String s = JSON.toJSONString(cartItemVo);
            cartOps.put(cartItemVo.getSkuId().toString(),s);
            return cartItemVo;

        }else{
            //购物车中已经有了该商品，只需更改其数量即可
            CartItemVo itemVo = JSON.parseObject(res, CartItemVo.class);
            itemVo.setCount(itemVo.getCount()+num);
            String s = JSON.toJSONString(itemVo);
            cartOps.put(skuId.toString(),s);
            return itemVo;
        }


    }

    @Override
    public CartItemVo getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String res = (String) cartOps.get(skuId.toString());
        CartItemVo cartItemVo = JSON.parseObject(res, CartItemVo.class);
        return cartItemVo;
    }

    /**
     * 获取用户登录或者未登录购物车里所有的数据
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Override
    public CartVo getCart() throws ExecutionException, InterruptedException {
        CartVo cartVo = new CartVo();
        //得到当前用户的信息
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId() != null){
            //已经登录
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            //判断是否有临时购物车
            String tempCartKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItemVo> tempCartItems = getCartItems(tempCartKey);
            if(tempCartItems != null){
                //有临时购物车，进行合并
                for (CartItemVo tempCartItem : tempCartItems) {
                    addToCart(tempCartItem.getSkuId(), tempCartItem.getCount());
                }
                //清空临时购物车
                clearCart(tempCartKey);
            }
            List<CartItemVo> cartItems = getCartItems(cartKey);
            cartVo.setItems(cartItems);
        }else{
            //没有登录，获取临时购物车的数据
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItemVo> cartItems = getCartItems(cartKey);
            cartVo.setItems(cartItems);
        }

        return cartVo;
    }

    //根据key 获取购物车的所有商品
    private List<CartItemVo> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        return values.stream().map((obj) -> {
            String s = (String) obj;
            CartItemVo cartItemVo = JSON.parseObject(s, CartItemVo.class);
            return cartItemVo;
        }).collect(Collectors.toList());
    }

    private BoundHashOperations<String, Object, Object> getCartOps() {
        //得到当前用户的信息
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = "";
        if(userInfoTo.getUserId() != null){
            //登录了 //gulimall:cart:1
            cartKey = CART_PREFIX+ userInfoTo.getUserId();
        }else{
            //临时用户
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        return operations;
    }
    @Override
    public void clearCart(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {

        //查询购物车里面的商品
        CartItemVo cartItem = getCartItem(skuId);
        //修改商品状态
        cartItem.setCheck(check == 1?true:false);

        //序列化存入redis中
        String redisValue = JSON.toJSONString(cartItem);

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(),redisValue);

    }

    /**
     * 修改购物项数量
     * @param skuId
     * @param num
     */
    @Override
    public void changeItemCount(Long skuId, Integer num) {

        //查询购物车里面的商品
        CartItemVo cartItem = getCartItem(skuId);
        cartItem.setCount(num);

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        //序列化存入redis中
        String redisValue = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),redisValue);
    }


    /**
     * 删除购物项
     * @param skuId
     */
    @Override
    public void deleteIdCartInfo(Integer skuId) {

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    /**
     * 查询当前用户的购物车中的商品
     * @return
     */
    @Override
    public List<CartItemVo> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId() == null){
            return null;
        }else {
            String cartKey = CART_PREFIX+ userInfoTo.getUserId();
            List<CartItemVo> cartItems = getCartItems(cartKey);
            List<CartItemVo> collect = cartItems.stream().map((item)->{
                //因为购物车中可能是很久之前放入的，所以需要再次查询商品的最新价格
                BigDecimal price = productFeignService.getPrice(item.getSkuId());
                item.setPrice(price);
                return item;
                //过滤被选中的商品
            }).filter(item -> item.getCheck()).collect(Collectors.toList());
            return collect;
        }

    }

}
